﻿using System.Globalization;
using System.Linq;
using System.Text;
using InfiniTec.Exchange.Notifications.Microsoft.Exchange.WebServices;

namespace InfiniTec.Exchange.Notifications
{
	internal static class ResponseMessageTypeExtension
	{
		public static void EvaluateAndThrowIfNecessary(this ResponseMessageType message)
		{
			if (message.ResponseClass ==
				ResponseClassType.Success) return;

			ResponseCodeType? code = (message.ResponseCodeSpecified) ? (ResponseCodeType?)message.ResponseCode : null;

			var description = new StringBuilder();
			description.AppendLine(message.MessageText);

			if (message.MessageXml != null && message.MessageXml.Any != null &&
				message.MessageXml.Any.Length > 0)
			{
				description.Append("Affected properties: ");

				description.Append(string.Join(", ", message.MessageXml.Any.Select(element => element.OuterXml).ToArray()));
			}

			throw new WebServiceInvocationFailedException(description.ToString(), ((object) code ?? "(unkwown)").ToString(), string.Format(CultureInfo.CurrentCulture, "A call to the Exchange WebServices failed. Error: {0}; {1}", (object)code ?? "(null)", description));
		}
	}
}
